package com.gitee.feizns.web.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feizns
 * @since 2019/4/12
 */
public abstract class WebUtils {

    /**
     * 所有需要处理的代理请求头
     */
    private static final String[] HEADERS = { "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "X-Real-IP" };

    /**
     * 获取用户真实ip
     * @link https://www.cnblogs.com/xiaoxing/p/6565573.html
     * @return
     */
    public static String getIpAddress() {
        HttpServletRequest req = getReq();
        for (String header : HEADERS) {
            String val = req.getHeader(header);
            if ( ipValidate(val) )
                return val.split(",")[0];
        }
        return req.getRemoteAddr();
    }

    private static boolean ipValidate(String val) {
        return val != null
                && val.length() != 0
                && "unknown".equalsIgnoreCase(val) == false;
    }


    public static String getHeader(String header) {
        return getReq().getHeader(header);
    }

    public static void setHeader(String name, String val) {
        getResp().setHeader(name, val);
    }

    /**
     * 获取
     * @return
     */
    public static String getUserAgent() {
        return getReq().getHeader("User-Agent");
    }



    /**
     * 获取请求
     * 在异步环境下跑 会有问题.
     * @return
     */
    public static HttpServletRequest getReq() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResp() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }



    /**
     * 获取当前服务器地址
     * @return
     */
    public static String getBasePath() {
        HttpServletRequest req = getReq();
        return req.getScheme() + "://"
                + req.getServerName()
                + (req.getServerPort() == 80 ? "" : ":" + req.getServerPort())
                + req.getContextPath();
    }

}
